<template>
	<van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="onClickLeft" />
	<div>
		<van-image width="100%" height="200" :src="goods.url" />
		<h3>商品名称: {{ goods.name }}</h3>
		<p>商品描述: {{ goods.description }}</p>
	</div>
	<van-action-bar>
		<van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24" />
		<van-action-bar-icon icon="cart-o" text="购物车" />
		<van-action-bar-icon icon="star" text="已收藏" color="#ff5000" />
		<van-action-bar-button type="warning" text="加入购物车" @click="bindAddCart"/>
		<van-action-bar-button type="danger" text="立即购买" />
	</van-action-bar>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { showSuccessToast } from 'vant';

const route = useRoute() // 路由信息对象
const router = useRouter() //路由对象

const goods = ref({})

const getGoodsDetail = id => {
	axios({
		url: `http://localhost:3000/goods/${id}`,
		method: 'GET',
	}).then(res => {
		const data = res.data //获取服务端返回数据
		if (data.code == 1) {
			goods.value = data.goods
		}
	})
}

/**
 * 加入购物车
 */
const bindAddCart = ()=>{
	// 判断商品是否已经在购物车中，如果已经存在，数量加一，
	axios({
		url:'http://localhost:3000/cart',
		method:'POST',
		data:{
			name:goods.value.name,
			url:goods.value.url,
			price:goods.value.price,
			num:1,
			description:goods.value.description,
			state:0
			
		}
	}).then(res=>{
		const data = res.data
		if(data.code == 1){
			showSuccessToast('加入购物车成功！');
		}
	})
}

/**
 * 返回
 */
const onClickLeft = () => {
	router.back()
}

onMounted(() => {
	const id = route.query.id
	getGoodsDetail(id)
})
</script>

<style lang="css" scoped>
.m-title {
	height: 40px;
	text-align: center;
	background-color: #f5f7fa;
	font-size: 18px;
	line-height: 40px;
}
</style>
